package com.yylending.las.authority.login;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.*;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yylending.las.Constants;
import com.yylending.las.YJKD;
import com.yylending.las.authority.Account;
import com.yylending.las.authority.rsa.RSAEncodePresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by laixj on 2017/8/4.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class LoginPresenter extends RSAEncodePresenter<Model, LoginPresenter.View> {
	private final static String TAG = "LoginPresenter";

	public static class Generator implements PresenterFactory<LoginPresenter> {
		@Override
		public LoginPresenter create() {
			return new LoginPresenter();
		}
	}

	public interface View extends IView {
		void loginSuccess();

		void loginFail(String msg);

		void loginRetCode(String retCode);
	}

	private View mView;
	private String mRequestPage;

	@Override
	public void attach(LoginPresenter.View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new LoginModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		return params;
	}

	public void login(String phone, String pwd, String longitude, String latitude) {
		LoginModel.LoginAccount account = new LoginModel.LoginAccount(phone, pwd, longitude, latitude);
		execute(account, LoginModel.METHOD_LOGIN, false, phone, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void loginResult(LoginModel.LoginResult result) {
		if (mRequestPage.equals(result.requestPage)) {
			if (BaseResultEntity.isResponseSuccess(result) && null != result.getData()) {
				Account rs = result.getData();
				YJKD.loginSuccess(rs, (String) result.extraParam);
				EventAgent.postSticky(new IEvent.LoginSuccessEvent(IEvent.CODE_LOGIN_SUCCESS));
				mView.loginSuccess();
			} else {
				YJKD.loginFailed(ResponseCode.CODE_DECODE_FAIL.equalsIgnoreCase(result.getRetCode()));
				if (ResponseCode.CODE_DECODE_FAIL.equalsIgnoreCase(result.getRetCode())) {
					mView.loginFail(Constants.MSG_LOGIN_FAIL);
				} else {
					String msg = result.getRetMsg();
					mView.loginFail(TextUtils.isEmpty(msg) ? "" : msg);
				}
			}
			mView.loginRetCode(result.getRetCode());
		}
	}
}
